package com.bifrost.repository;

import com.bifrost.entity.Order;
import com.bifrost.entity.OrderItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author rangf
 * @date 2017/12/4
 */
public interface OrderItemRepository extends JpaRepository<OrderItem, Long> ,JpaSpecificationExecutor<OrderItem> {

    OrderItem findByOrderAndSkuId(Order order, Long skuId);

    @Modifying
    @Transactional
    @Query(value = "UPDATE ORDER_ITEM SET `STATUS`=NULL WHERE ORDER_ID=?1 AND SKU_ID=?2", nativeQuery = true)
    int updateOrderItemStatus(Long orderId, Long skuId);

    @Modifying
    @Transactional
    @Query(value = "UPDATE ORDER_ITEM SET RETURN_QUANTITY=RETURN_QUANTITY-?3 WHERE ORDER_ID=?1 AND SKU_ID=?2", nativeQuery = true)
    int updateOrderItemReturnQUantity(Long orderId, Long skuId, Integer quantity);

    /**
     * 注意！！！该方法返回的OrderItem实体只包含orderItemId、externalId、
     * skuPrice、skuQuantity属性
     * @param order
     * @return
     */
    @Query("select new OrderItem (o.orderItemId,o.externalId,o.skuPrice,o.skuQuantity)from OrderItem o where o.order =?1")
    List<OrderItem> findByOrder(Order order);


    OrderItem findByCouponCode(long couponCode);
}
